#!/usr/bin/env python
# -*- coding: UTF-8 -*-

'''
Copyright (C) 2011 dbzhang800@gmail.com
All rights reserved.
'''
import math
try:
    from PySide import QtCore, QtGui
except ImportError:
    from PyQt4 import QtCore, QtGui

class Widget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        self.setWindowTitle(u"For refine's res file 2011.12.16")
        self.edit = QtGui.QPlainTextEdit()
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(QtGui.QLabel("<font color=blue>Drag a file and Drop it here</font>"))
        vbox.addWidget(self.edit)
        self.setLayout(vbox)

        self.edit.setAcceptDrops(False)
        self.setAcceptDrops(True)

        self.resize(400, 300)

    def dragEnterEvent(self, evt):
        if evt.mimeData().hasFormat("text/uri-list"):
            evt.acceptProposedAction()

    def dropEvent(self, evt):
        urls = evt.mimeData().urls()
        if not urls:
            return
        for url in urls:
            self.openOneFile(url.toLocalFile())
            self.edit.appendPlainText("")

    def openOneFile(self, filename):
        if not filename.endswith(".res"):
            self.edit.appendHtml("<font color=red>Error:</font><b>%s</b> not endswith .res, skip ..." % filename)
            return

        with file(filename) as f:
            lines = f.readlines()
            nu0 = -1
            for nu in range(len(lines)):
                if lines[nu].startswith("***** ABERRATIONS (Microns) AND BEAM LANDING ANGLES (Degrees) *****"):
                    nu0 = nu
                    break
            if nu0 == -1:
                self.edit.appendHtml("<font color=red>Error:</font><b>%s</b> not an valid refine file, skip1 ..." % filename)
                return
            if not (lines[nu0+3].startswith("AXIAL") and lines[nu0+4].startswith("MAIN-FIELD")):
                self.edit.appendHtml("<font color=red>Error:</font><b>%s</b> not an valid refine file, skip2 ..." % filename)
                return
            axial_items = lines[nu0+3].split()
            mainfield_items = lines[nu0+4].split()
            if not (len(axial_items) == 8 and len(mainfield_items) == 8):
                print len(axial_items), len(mainfield_items)
                self.edit.appendHtml("<font color=red>Error:</font><b>%s</b> not an valid refine file, skip3 ..." % filename)
                return
            try:
                axial_sa = float(axial_items[1])
                axial_ca = float(axial_items[6])
                main_co = float(mainfield_items[2])
                main_fc = float(mainfield_items[3])
                main_as = float(mainfield_items[4])
                main_ca = float(mainfield_items[6])
                main_la = float(mainfield_items[7])
            except:
                self.edit.appendHtml("<font color=red>Error:</font><b>%s</b> not an valid refine file, skip4 ..." % filename)
                return
            axial_a = math.sqrt(axial_sa*axial_sa + axial_ca*axial_ca)
            main_a = math.sqrt(main_co*main_co + main_fc*main_fc + main_as*main_as + main_ca*main_ca + main_la*main_la)

            self.edit.appendHtml("<font color=green>OK:</font>%s" % filename)
            self.edit.appendHtml("<b>AXIAL:sqrt(sa*sa+ca*ca)</b><br> %f" % axial_a)
            self.edit.appendHtml("<b>MAIN-FIELE:sqrt(co*co+fc*fc+as*as+ca*ca+la*la)</b><br> %f" % main_a)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())
